package com.dyrnq.seckill.service.impl;

import com.dyrnq.seckill.entity.OrderInfo;
import com.dyrnq.seckill.entity.SeckillOrder;
import com.dyrnq.seckill.mapper.OrderInfoMapper;
import com.dyrnq.seckill.mapper.SeckillGoodsMapper;
import com.dyrnq.seckill.mapper.SeckillOrderMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@RequiredArgsConstructor
public class SeckillOrderService {
    private final SeckillOrderMapper seckillOrderMapper;
    private final OrderInfoMapper orderInfoMapper;
    private final SeckillGoodsMapper seckillGoodsMapper;

    public void insert(long goods_id, long user_id) {
        int effect = seckillGoodsMapper.updateStockCountById(goods_id, 1);
        if (effect == 0) {
            throw new RuntimeException("扣减库存异常");
        }
        insert_unconditionally(goods_id, user_id);
    }

    public void insert_unconditionally(long goods_id, long user_id) {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(LocalDateTime.now());
        orderInfo.setGoodsId(goods_id);
        orderInfo.setUserId(user_id);
        orderInfo.setStatus(0);
        orderInfoMapper.insert(orderInfo);

        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setOrderId(orderInfo.getId());
        seckillOrder.setUserId(user_id);
        seckillOrder.setGoodsId(goods_id);
        seckillOrderMapper.insert(seckillOrder);
    }

}
